package io.yunho.yunho.interview.two.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone implements Runnable{
    /**
     * synchronized 可重入锁演示
     */
    public synchronized void sendSMS(){
        System.out.println(Thread.currentThread().getName()+"\t #####发送短信");
        sendEmail();
    }
    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName()+"\t #####发送邮件");
    }

    /**
     * ReentrantLock 可重入锁演示
     */
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        runGet();
    }

    private void runGet() {//可以加两把锁 需要注意加锁 与 解锁 一一对应 缺一不可
        lock.lock();
//        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t #####run Get");
            runSet();
        }finally {
            System.out.println(Thread.currentThread().getName()+"\t #####run Get finally");
            lock.unlock();
//            lock.unlock();
        }
    }
    private void runSet() {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t #####run Set");
        }finally {
            System.out.println(Thread.currentThread().getName()+"\t #####run Set finally");
            lock.unlock();
        }
    }
}
/**
 * @author: Jason
 * @date: 2021/3/16 9:02
 * @description:
 * 可重入锁（也叫递归锁）
 *
 * 指的是统一线程外层函数获得锁之后，内层递归函数仍然能获取该锁的代码，
 * 在同一个线程外层方法获取锁的时候，在进入内层放放会自动获取锁
 * 也就是说，线程可以进入任何一个它已经拥有的锁所同步着的代码块。
 *
 */
public class ReenterLockTest {
    public static void main(String[] args) {

        Phone phone = new Phone();
        new Thread(()->{
            phone.sendSMS();
        },"01").start();
        new Thread(()->{
            phone.sendSMS();
        },"02").start();
        try {
            TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        Thread t3 = new Thread(phone,"t3");
        Thread t4 = new Thread(phone,"t4");
        t3.start();
        t4.start();
    }
}
